#! /bin/bash
#<instruction> 
#err="至少要一个参数"
#test translate == ""
#echo $USER: translate: $err && exit 1


#!/bin/bash
# access translate.google.com from terminal

#mytrans(){
	#help='translate <text> [[<source language>] <target language>]
	#if target missing, use DEFAULT_TARGET_LANG
	#if source missing, use auto'

	## adjust to taste
	#DEFAULT_TARGET_LANG=en

	#if [[ $1 = -h || $1 = --help ]]
	#then
		#echo "$help"
		#exit
	#fi

	#if [[ $3 ]]; then
		#source="$2"
		#target="$3"
	#elif [[ $2 ]]; then
		#source=auto
		#target="$2"
	#else
		#source=auto
		#target="$DEFAULT_TARGET_LANG"
	#fi

	#result=$(curl -s -i --user-agent "" -d "sl=$source" -d "tl=$target" --data-urlencode "text=$1" http://translate.google.cn/?hl=en)
	#encoding=$(awk '/Content-Type: .* charset=/ {sub(/^.*charset=["'\'']?/,""); sub(/[ "'\''].*$/,""); print}' <<<"$result")
	##iconv -f $encoding <<<"$result" | awk 'BEGIN {RS="<div"};/<span[^>]* id=["'\'']?result_box["'\'']?/ {sub(/^.*id=["'\'']?result_box["'\'']?(>| [^>]*>)([ \n\t]*<[^>]*>)*/,"");sub(/<.*$/,"");print}' | html2text -utf8
	#echo "$1: "$(iconv -f $encoding <<<"$result" | awk 'BEGIN {RS="</div>"};/<span[^>]* id=["'\'']?result_box["'\'']?/' | html2text -utf8)
#}

#if [[ "$1" == "" ]];then
	#google-chrome http://translate.google.cn/?hl=zh-CN#en/zh-CN/ &
	#exit
#elif [[ "$(echo $1|grep -P '^([a-z]|[A-Z])*$')" == "" ]];then
	#mytrans "$1" zh_CN en
#else
	#mytrans "$1" en zh_CN
#fi

#http://fy.webxml.com.cn/webservices/EnglishChinese.asmx

if [[ "$1" != "-w" ]]; then
	dict True $@
else
	shift
	wordkey=""

	if [[ "$(echo $@|grep -P '^([a-zA-Z ])*$')" == "" ]];then
		wordkey=$1
		curl --silent 'http://fy.webxml.com.cn/webservices/EnglishChinese.asmx/TranslatorString?wordKey='$1 | xml2 | sed '1,3d;s#/ArrayOfString/string=##g;/^\/ArrayOfString\/string/d;$d'
	else
		#wordkey=$(echo $@ | tr ' ' '+')
		wordkey=$(tr ' ' '+' <<< $@)
		curl --silent 'http://fy.webxml.com.cn/webservices/EnglishChinese.asmx/TranslatorString?wordKey='${wordkey[@]} | xml2 | sed '1,3d;s#/ArrayOfString/string=##g;/^\/ArrayOfString\/string/d;$d' | awk '{if(NR==2){print "["$0"]"}else{print}}' | sed '1N;s/\n/ /'
	fi

	#echo ${wordkey[@]}
	echo
	curl --silent http://fy.webxml.com.cn/webservices/EnglishChinese.asmx/TranslatorSentenceString?wordKey=${wordkey[@]} | xml2 | sed '1,3d;s#/ArrayOfString/string##g;s/^=//g;s/|/\n/g'
fi
